import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../stores/user'
import router from '../router/index'
const instance = axios.create({
  baseURL: 'http://localhost:5501',
  timeout: 5000
})

instance.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    //携带token
    const token = userStore.getToken()
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (res) => {
    if (res.data.message === '身份认证失败！') {
      ElMessage.error(res.data.message)
      console.log(res.data);
      router.push('/login')
      return Promise.reject(res.data.message)
    }
    if (res.data.status === 1 && res.data.message === '获取预约信息失败！') {
      return res.data
    }
    if (res.data.status === 1) {
      ElMessage.error(res.data.message)
      return Promise.reject(res.data.message)
    } 
    return res.data
  },
  (error) => {
    return Promise.reject(error)
  }
)

export default instance
